<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="账号" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="realname">
        <el-input
          v-model="queryParams.realname"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电子邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入电子邮箱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.ClientUserStatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['client:user:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="userList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="头像" width="60" align="center" prop="avatar">
        <template slot-scope="scope">
          <el-avatar
            v-if="scope.row.avatar"
            shape="square"
            size="medium"
            :src="qiniuUrl + scope.row.avatar"
          />
          <el-avatar v-else shape="square" size="medium">
            <i class="el-icon-user" />
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column
        label="账号"
        width="150"
        align="center"
        prop="username"
      />
      <el-table-column
        label="姓名"
        width="150"
        align="center"
        prop="realname"
      />
      <el-table-column label="手机号" align="center" prop="mobile" />
      <el-table-column label="电子邮箱" align="center" prop="email" />
      <el-table-column label="年龄" width="50" align="center" prop="age" />
      <el-table-column label="性别" width="50" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.SysUserSex" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.ClientUserStatus"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['client:user:edit']"
            >修改</el-button
          >
          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['client:user:edit']"
          >
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                command="handleUpdateStatus"
                :icon="
                  scope.row.status == 1 ? 'el-icon-lock' : 'el-icon-unlock'
                "
                v-hasPermi="['client:user:edit']"
                >{{
                  scope.row.status == 1 ? '停用账号' : '启用账号'
                }}</el-dropdown-item
              >
              <el-dropdown-item
                command="handleResetPwd"
                icon="el-icon-key"
                v-hasPermi="['client:user:edit']"
                >重置密码</el-dropdown-item
              >
              <el-dropdown-item
                command="handleRemoveDept"
                icon="el-icon-delete"
                v-hasPermi="['client:user:removeDept']"
                >移除机构</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="账号" prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入账号"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="账号" prop="realname">
          <el-input v-model="form.realname" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入电子邮箱" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改密码对话框 -->
    <el-dialog
      title="重置密码"
      :visible.sync="openResetPwd"
      width="500px"
      append-to-body
    >
      <el-form
        ref="resetPwdForm"
        :model="resetPwdForm"
        :rules="resetPwdRules"
        label-width="80px"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="resetPwdForm.username" :disabled="true" />
        </el-form-item>
        <el-form-item label="姓名" prop="realname">
          <el-input v-model="resetPwdForm.realname" :disabled="true" />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="resetPwdForm.password"
            placeholder="请输入新的用户密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitResetPwd">确 定</el-button>
        <el-button @click="cancelResetPwd">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import md5 from 'js-md5';
import {
  listUser,
  getUser,
  addUser,
  updateUser,
  resetPwd,
  changeStatus,
  removeDept,
} from '@/api/client/user';

export default {
  name: 'User',
  dicts: ['SysUserSex', 'ClientUserStatus'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生用户表格数据
      userList: [],
      // 弹出层标题
      title: '',
      // 弹出层是否是修改框
      isEdit: true,
      // 是否显示弹出层
      open: false,
      openResetPwd: false,
      // 头像地址
      qiniuUrl: process.env.VUE_APP_QINIU_URL,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: null,
        mobile: null,
        email: null,
        nickname: null,
        age: null,
        sex: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            min: 6,
            max: 20,
            message: '账号在 6 到 20 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          {
            min: 6,
            max: 20,
            message: '密码在 6 到 20 个字符',
            trigger: 'blur',
          },
        ],
      },
      // 修改密码表单
      resetPwdForm: {
        username: '',
        realname: '',
        password: '',
      },
      resetPwdRules: {
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          {
            min: 6,
            max: 20,
            message: '密码在 6 到 20 个字符',
            trigger: 'blur',
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询学生用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then((response) => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        avatar: null,
        username: null,
        mobile: null,
        email: null,
        password: null,
        nickname: null,
        age: null,
        sex: null,
        intro: null,
        birthday: null,
        school: null,
        status: null,
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isEdit = false;
      this.title = '添加学生用户';
    },
    handleResetPwd(row) {
      this.resetPwdForm = {
        userId: row.userId,
        username: row.username,
        realname: row.realname,
      };
      this.openResetPwd = true;
    },
    cancelResetPwd() {
      this.resetPwdForm = {};
      this.openResetPwd = false;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleUpdateStatus':
          this.handleUpdateStatus(row);
          break;
        case 'handleResetPwd':
          this.handleResetPwd(row);
          break;
        case 'handleRemoveDept':
          this.handleRemoveDept(row);
          break;
        default:
          break;
      }
    },
    /** 修改操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids;
      getUser(userId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.isEdit = true;
        this.title = '修改用户信息';
      });
    },
    handleRemoveDept(row) {
      this.$confirm(`将【${row.username}】学生从机构移出，请谨慎操作！`)
        .then(() => {
          removeDept({
            userId: row.userId,
          }).then((response) => {
            this.$modal.msgSuccess('学生账号已移除！');
            this.getList();
          });
        })
        .catch(() => {
          this.$modal.msgSuccess('取消操作');
        });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.userId != null) {
            updateUser(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            if (!this.form.password || this.form.password == '') {
              this.$message.error('请输入用户初识密码');
              return;
            } else {
              this.form.password = md5(this.form.password);
            }
            addUser(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitResetPwd() {
      this.$refs['resetPwdForm'].validate((valid) => {
        if (valid) {
          this.resetPwdForm.password = md5(this.resetPwdForm.password);
          resetPwd(this.resetPwdForm).then((response) => {
            this.$modal.msgSuccess('密码重置成功');
            this.openResetPwd = false;
          });
        }
      });
    },
    handleUpdateStatus(row) {
      let oldStatus = row.status;
      let newStatus = '';
      let oper = '';
      if (oldStatus == '1') {
        // 停用账号
        oper = '停用';
        newStatus = '2';
      } else {
        // 启用账号
        oper = '启用';
        newStatus = '1';
      }
      this.$confirm(`是否${oper}【${row.username}】用户账号？`)
        .then(() => {
          changeStatus({
            userId: row.userId,
            status: newStatus,
          }).then((response) => {
            this.$modal.msgSuccess('状态修改成功');
            this.getList();
          });
        })
        .catch(() => {
          this.$modal.msgSuccess('取消操作');
        });
    },
  },
};
</script>
